package com.loongtech.bi.action.system;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.Utils;

@Controller("chgPasswordAction")
@Scope("view")
public class ChgPasswordAction implements java.io.Serializable {
	private static final long serialVersionUID = 5L;
	@Autowired
	private Session session;
	private String userName;
	private String oldPassword;
	private String newPassword;
	@Autowired
	private SysUserManager sysUserManager;
	@Autowired
	private SysLogManager sysLogManager;
	
	@Autowired
	public void init() {
		userName = session.getUserName();
		oldPassword="";
		newPassword="";
	}

	public void change() {
		FacesContext context = FacesContext.getCurrentInstance();

		// 判断参数
		if (null == userName || userName.isEmpty()) {
			context.addMessage(null, new FacesMessage("修改密码失败", "用户名为空!"));
			return;
		}
		if (null == oldPassword || oldPassword.isEmpty()) {
			context.addMessage(null, new FacesMessage("修改密码失败", "旧密码为空!"+userName));
			return;
		}
		if (null == newPassword || newPassword.isEmpty()) {
			context.addMessage(null, new FacesMessage("修改密码失败", "新密码为空!"+userName));
			return;
		}
		EntitySysUser curUser= sysUserManager.getBy(EntitySysUser.K.username, userName);
		if(null == curUser || null == curUser.getPassword()){
			context.addMessage(null, new FacesMessage("修改密码失败", "用户不存在!"+userName));
			return;
		}
		if(!curUser.getPassword().equals(Utils.md5(oldPassword))){
			context.addMessage(null, new FacesMessage("修改密码失败", "原密码错误!"+userName));
			return;
		}		
		//保存数据，记录日志
		curUser.setPassword(Utils.md5(newPassword));
		sysUserManager.merge(curUser);
		sysLogManager.addLog(userName, "修改密码成功"+userName);
		context.addMessage("修改密码成功", new FacesMessage("修改密码成功", "修改密码成功!"+userName));
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}	 
}
